﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using RingSong.ViewModels;
using System.Collections.Generic;
using System.IO.IsolatedStorage;
using System.IO;
using System.Linq;
using Microsoft.Phone.BackgroundTransfer;
using System.ComponentModel;
using System.Threading;

namespace RingSong.Function
{

    public class Down
    {
        public static List<RingViewModel> lst = new List<RingViewModel>();
        public static bool isLoadingDown=false;
        public static void Download()
        {
            if (BackgroundTransferService.Requests.Count() > 5) return;
            string url = ""; string Infoid = "";

            for (int i = 0; i < lst.Count; i++)
            {
                bool a = false;
                if (BackgroundTransferService.Requests.Count() > 0) //若已经有下载就比对出一个lst中没有被下载的拿出来下载
                {
                    //Requests集合里所有都对比一遍，如果没有才行
                    int count=0;
                    foreach (BackgroundTransferRequest b in BackgroundTransferService.Requests)
                    {
                        if (b.Tag != lst[i].Infoid) count++;
                    }
                    if (count == BackgroundTransferService.Requests.Count())
                    {
                        url = lst[i].Downurl;
                        Infoid = lst[i].Infoid;
                        if (!Anm.isShowWait.Contains(lst[i]))
                            Anm.CloseOne(lst[i], MainPage.lst);
                        Anm.Show_Hide(lst[i], "pro", true, MainPage.lst);
                        a = true;
                        continue;
                    }
                    else
                    { 
                        return ;
                    }
                }
                else
                {
                    url = lst[0].Downurl;
                    Infoid = lst[0].Infoid;
                    a = true;
                }
                if (a) continue;
            }
            IEnumerator<BackgroundTransferRequest> BackgroundRequestList = BackgroundTransferService.Requests.GetEnumerator();
            ///这里 保存路径必须是shared/transfers/，我看到MSDN里面有人直接写transfers/，但是我写就报错。。
            string filename = "shared/transfers/" + Infoid + ".mp3";
            IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
            if (myIsolatedStorage.FileExists(filename))
                myIsolatedStorage.DeleteFile(filename);//若存在就删除

            
            Uri SaveUri = new Uri(filename, UriKind.Relative);
            BackgroundTransferRequest BackgroundRequest = new BackgroundTransferRequest(new Uri(url, UriKind.Absolute), SaveUri);
            BackgroundRequest.Tag = Infoid;
            BackgroundRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
            BackgroundRequest.TransferProgressChanged += new EventHandler<BackgroundTransferEventArgs>(BackgroundRequest_TransferProgressChanged);
            BackgroundRequest.TransferStatusChanged += new EventHandler<BackgroundTransferEventArgs>(BackgroundRequest_TransferStatusChanged);

            //pro.ID = BackgroundRequest.RequestId;
            //注册后台下载
            BackgroundWorker bkgWork = new BackgroundWorker();
            bkgWork.DoWork += delegate(object s, DoWorkEventArgs args)
            {
                isLoadingDown = true;
                BackgroundTransferService.Add(BackgroundRequest);
            };
            bkgWork.RunWorkerAsync();
        }

        public static int CountDown()
        {
            return BackgroundTransferService.Requests.Count();
        }

        static void BackgroundRequest_TransferStatusChanged(object sender, BackgroundTransferEventArgs e)
        {
            IEnumerator<BackgroundTransferRequest> BackgroundRequestList = BackgroundTransferService.Requests.GetEnumerator();
            while (BackgroundRequestList.MoveNext())
            {
                if (BackgroundRequestList.Current.RequestId == e.Request.RequestId)
                {
                    if (BackgroundRequestList.Current.TransferStatus == TransferStatus.Completed)
                    {
                        for (int i = 0; i < lst.Count;i++ )
                        {
                            if (lst[i].Infoid == BackgroundRequestList.Current.Tag)
                            {
                                isLoadingDown = false;
                                lst[i].Progress = 100;
                                Com.UpdateDict(lst[i]);
                                Anm.CloseOne(lst[i], MainPage.lst);
                                lst.Remove(lst[i]); 
                            }
                        }
                        BackgroundTransferService.Remove(
                           BackgroundTransferService.Find(BackgroundRequestList.Current.RequestId));
                        if (lst.Count != 0) Download();  //下载下一个
                        else
                        {
                            MainPage.lst.SelectedIndex = -1;
                        }
                    }
                }
            }
        }
        static void BackgroundRequest_TransferProgressChanged(object sender, BackgroundTransferEventArgs e)
        {
            foreach (RingViewModel r in lst)
            {
                if (r.Infoid == e.Request.Tag)
                {
                    if (!Anm.isShowPro.Contains(r))
                        Anm.Show_Hide(r, "pro", true, MainPage.lst);
                    ///显示各个文件的进度
                    r.Progress = (double)((double)e.Request.BytesReceived / (double)e.Request.TotalBytesToReceive) * 100;
                }
            }
        }


    }
}
